package controller.ur;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import model.dao.CommentDaoLocal;
import model.dao.PhotoDaoLocal;
import model.dao.UserDaoLocal;
import model.entity.Comment;
import model.entity.Photo;
import model.entity.User;
import controller.CUtil;

/**
 * Servlet implementation class SPhotoAddComment
 */
public class SPhotoAddComment extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	@EJB
	private CommentDaoLocal commentDao;
	
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private UserDaoLocal userDao;
	
	private Logger log=Logger.getLogger(SPhotoAddComment.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SPhotoAddComment() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		request.setCharacterEncoding("UTF-8");
		
		int id=Integer.parseInt((String)request.getParameter("photoId"));
		User user=(User)request.getSession().getAttribute("user");
		Photo photo=photoDao.findById(id);
		String title=(String)request.getParameter("title");
		String content=(String)request.getParameter("content");
		Comment comment=new Comment();
		comment.setPhoto(photo);
		comment.setUser(user);
		comment.setTitle(title);
		comment.setContents(content);
		comment.setDate(new Date());
		photo.getComment().add(comment);
		commentDao.persist(comment);
		photoDao.merge(photo);
		
		User currentUser=userDao.findById(Integer.parseInt((String)request.getParameter("currentUserId")));
		String messageTitle="New comment add on photo: "+photo.getTitle();
		String messageText=messageTitle+". User added comment: "+currentUser.getFirstName()+" "+currentUser.getLastName()
				+". Content: "+comment.getContents();
		if(currentUser.getEmailNotifications()){
			CUtil.sendMail(messageTitle, messageText, currentUser.getEmail());
		}
		
		log.info("Comment added: "+comment.toString());
		
		CUtil.redirecter(request, response, "SViewPhoto?photoId="+id);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
